class Fraction {
    constructor(
        public numerator: number,
        public denominator: number = 1
    ) {
        this.simplify();
    }

    // 计算最大公约数
    private gcd(a: number, b: number): number {
        return b === 0 ? a : this.gcd(b, a % b);
    }

    // 约分
    private simplify(): void {
        if (this.numerator === 0) {
            this.denominator = 1;
            return;
        }

        const divisor = this.gcd(Math.abs(this.numerator), Math.abs(this.denominator));
        this.numerator /= divisor;
        this.denominator /= divisor;

        // 确保分母为正
        if (this.denominator < 0) {
            this.numerator = -this.numerator;
            this.denominator = -this.denominator;
        }
    }

    // 加法
    add(other: Fraction): Fraction {
        const newNumerator = this.numerator * other.denominator + other.numerator * this.denominator;
        const newDenominator = this.denominator * other.denominator;
        return new Fraction(newNumerator, newDenominator);
    }

    // 减法
    subtract(other: Fraction): Fraction {
        const newNumerator = this.numerator * other.denominator - other.numerator * this.denominator;
        const newDenominator = this.denominator * other.denominator;
        return new Fraction(newNumerator, newDenominator);
    }

    // 乘法
    multiply(other: Fraction): Fraction {
        const newNumerator = this.numerator * other.numerator;
        const newDenominator = this.denominator * other.denominator;
        return new Fraction(newNumerator, newDenominator);
    }

    // 除法
    divide(other: Fraction): Fraction {
        const newNumerator = this.numerator * other.denominator;
        const newDenominator = this.denominator * other.numerator;
        return new Fraction(newNumerator, newDenominator);
    }

    // 转换为字符串
    toString(): string {
        if (this.denominator === 1) {
            return this.numerator.toString();
        }
        return `${this.numerator}/${this.denominator}`;
    }

    // 转换为数值（可选）
    toNumber(): number {
        return this.numerator / this.denominator;
    }
}

// // 使用示例
// const a = new Fraction(1, 3);
// const b = new Fraction(2, 5);

// console.log(`a = ${a}`); // 1/3
// console.log(`b = ${b}`); // 2/5

// const result1 = a.multiply(b);
// console.log(`a × b = ${result1}`); // 2/15

// const result2 = a.add(b);
// console.log(`a + b = ${result2}`); // 11/15

// const result3 = a.divide(b);
// console.log(`a ÷ b = ${result3}`); // 5/6